#coding:utf-8
import os
import re
output_path="/Users/fiery/Desktop/admin_sql.md"
output_obj = open(output_path, 'a')
output_obj.write("[TOC]")
output_obj.write("\n")
try:
    for parent,dirs,files in os.walk("/Users/fiery/Desktop/sql"):
        print(parent, dirs, files)
        for file in files:
            if '.sql' in file:
                file = os.path.join(parent, file)
                file_object = open(file)
                try:
                    all_the_text = file_object.read()
                    table=re.findall(r"CREATE TABLE `([^`]+)`",all_the_text)
                    comment=re.findall(r"COMMENT='([^']+)'",all_the_text)
                    if len(table)==0:
                        continue
                    if len(comment)==0:
                        comment.append("")
                    output_obj.write("######"+table[0]+" "+comment[0])
                    output_obj.write("\n")
                    output_obj.write("| 字段 | 类型 | 注解 |")
                    output_obj.write("\n")
                    output_obj.write("| ---- | ---- | ---- |")
                    output_obj.write("\n")
                    result=re.findall(r"CREATE TABLE `[^`]+` \(([\s\S]+)PRIMARY KEY",all_the_text)
                    str = re.compile(r",|'|`|DEFAULT|NOT|NULL|AUTO_INCREMENT|COMMENT")
                    linestr = str.sub("", result[0])
                    lines=linestr.split('\n')
                    for line in lines:
                        if len(line)>0 :
                            cols=line.split(" ")
                            vals = []
                            for col in cols:
                                if len(col)>0:
                                    vals.append(col)
                            if len(vals)>0:
                                if len(vals)<3:
                                    vals.append("")
                                try:
                                    output_obj.writelines("| "+vals[0]+" | "+vals[1]+" | "+vals[2]+" |")
                                    output_obj.write("\n")
                                except Exception as e:
                                    print(vals)

                finally:
                    file_object.close()
finally:
    output_obj.close()

